<?php
use Workerman\Worker;
use Workerman\RedisQueue\Client;
require_once __DIR__ . '/vendor/autoload.php';
require_once 'worker_config.php';
require_once 'Indexer.php';
require_once 'utils.php';
require_once 'PicThumb.class.php';
require_once 'Document.php';

Worker::$stdoutFile = '/tmp/worker_stdout.log';

$worker = new Worker(WEBSOCKET_URL);
$worker->count = 5;
$rpc = new Yar_Client(RPC_URL);

$worker->onWorkerStart = function () use ($worker, $rpc) {
    $client = new Client('redis://' . REDIS_HOST . ':6379', ['auth' => REDIS_PASS]);

    // 订阅
    $client->subscribe('-pattern-add', function($data) {
        echo "add pattern with pid:" . $data['pid'] . "\n";
//        $indexer = new Indexer();
//        $indexer->add($data);
        $document = new Document();
        $document->save($data);
    });

    // 订阅
    $client->subscribe('-pattern-update', function($data) {
        echo "update pattern with pid:" . $data['pid'] . "\n";
//        $indexer = new Indexer();
//        $indexer->update($data);
        $document = new Document();
        $document->save($data);
    });

    // 订阅图片列队
    $client->subscribe('-image-queue', function ($filename) use ($worker, $rpc) {
        $dest = API_PATH . UPLOAD_DIR . date("Y-m-d");
        $otherImagesArray = [];

        // 剪切主图
        cutFile(IMAGE_PATH . $filename, $dest);

        // 剪切其它序号图片
        list($name, $ext) = explode('.', $filename);

        for ($i = 1; $i <= 5; $i++) {
            $filename_no = $name . "-0" . $i . '.' . $ext;

            // 如果序号文件存在
            if (file_exists(IMAGE_PATH . $filename_no)) {
                cutFile(IMAGE_PATH . $filename_no, $dest);
                $otherImagesArray[] = UPLOAD_DIR . date("Y-m-d") . '/' . $filename_no;
            }
        }

        // 生成缩略图
        $option = array(
            'type' => 'fit',
            'width' => 330,
            'height' => 240,
            'handler' => 'gd'
        );

        $source = $dest . '/' . $filename;

        $thumb_file = $dest . '/' . $name. '_thumb.' . $ext;
        $thumb = new PicThumb();
        $thumb->set_config($option);
        $thumb->create_thumb($source, $thumb_file);

        echo UPLOAD_DIR . date("Y-m-d") . '/' . $filename . "\n";

        // 更新数据库
        $picture = UPLOAD_DIR . date("Y-m-d") . '/' . $filename;
        $thumb   = UPLOAD_DIR . date("Y-m-d") . '/' . $name. '_thumb.' . $ext;
        $rpc->updateIndexByNo($name, $picture, $thumb,  $otherImagesArray);

        // 数量减1
        $redis = new Redis();
        $redis->connect(REDIS_HOST, 6379);
        $redis->auth(REDIS_PASS);
        $redis->decr("import_images_count");
    });

    // 订阅导入图片消息
    $client->subscribe("-import-images", function ($data) use ($client) {
        if ($data) {
            $list = [];

            $files = scandir(IMAGE_PATH);
            foreach ($files as $file) {
                list($filename, $ext) = explode('.', $file);

                if (strtolower($ext) == "gif"
                    or strtolower($ext) == "jpg"
                    or strtolower($ext) == "png"
                    or strtolower($ext) == "jpeg") {

                    // 把不包含序号的图片
                    if (!strstr($filename, '-')) {
                        $client->send("-image-queue", $file);
                    }
                }
            }
        }
    });
};

//当有客户端发来消息时执行的回调函数(微信小程序的话,可以接受order_no(或者openid)作为uid传过来)
$worker->onMessage = function($connection, $data)
{
    global $worker;
    $json = json_decode($data, true);

    if (isset($json['command'])) {
        // 列表图片数量
        if ($json['command'] == 'files') {
            // 获取图片列表
            $list = listImages(IMAGE_PATH);

            // 计算文件数量
            $json['data'] = count($list);

            // 发送数据
            $connection->send(json_encode($json));
        }

        // 导入图片
        if ($json['command'] == 'import') {
            $redis = new Redis();
            $redis->connect(REDIS_HOST, 6379);
            $redis->auth(REDIS_PASS);

            $client = new Client('redis://' . REDIS_HOST . ':6379', ['auth' => REDIS_PASS]);

            // 获取图片列表
            $images = listImages(IMAGE_PATH);

            $redis->set("import_images_count", count($images));

            foreach ($images as $image) {
                $client->send("-image-queue", $image);
            }

            $json = [
                'command' => 'import',
                'data'   => count($images)
            ];

            $connection->send(json_encode($json));
        }

        if ($json['command'] == 'import_images_count') {
            $redis = new Redis();
            $redis->connect(REDIS_HOST, 6379);
            $redis->auth(REDIS_PASS);

            $count = $redis->get("import_images_count");

            $json = [
                'command' => 'import_images_count',
                'data'   => $count
            ];

            $connection->send(json_encode($json));
        }
    }
};

//当有客户端连接断开时,删除映射
$worker->onClose = function($connection) {
    global $worker;

    echo 'client close';
};

Worker::runAll();
